﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Gateway.Interfaces;
using PServiceBus.Gateway.ZeroMQ.DTO;
using PServiceBus.Gateway.Interfaces.DTO;

namespace PServiceBus.Gateway.ZeroMQ {
    public class ZeroMQGatewayService : IGatewayService {
        #region IMessageService Members

        public IGatewayServer Server { get; set; }

        public void RegisterRequestResponse() {
            Server.Register<ZeroMQESBRequest, ZeroMQESBTopicInfo>(SelectTopic);
            Server.Register<ZeroMQESBRequest, ZeroMQSubscriberInfo>(SelectSubscriber);
            Server.Register<ZeroMQESBRequest, ZeroMQTopicInfos>(GetTopics);
        }

        #endregion

        private static ZeroMQSubscriberInfo ToZeroMQSubscriber(SubscriberInfo subscriber) {
            var zsub = new ZeroMQSubscriberInfo();
            zsub.Durable = subscriber.Durable;
            zsub.ID = subscriber.ID;
            zsub.IsValid = subscriber.IsValid;
            zsub.Name = subscriber.Name;
            zsub.Topics = subscriber.Topics;
            zsub.Transports = subscriber.Transports;
            return zsub;
        }

        private static ZeroMQSubscriberInfo SelectSubscriber(ZeroMQESBRequest request) {
            var subscriber = MessageServiceBase.GetMessageBus(request.UserContext, reThrowException: request.ReThrowException, headers: request.Headers)
                .SelectSubscriber(request.Input, request.Headers);
            return ToZeroMQSubscriber(subscriber);
        }

        private static ZeroMQESBTopicInfo SelectTopic(ZeroMQESBRequest request) {
            return ZeroMQESBTopicInfo.New(MessageServiceBase.GetMessageBus(request.UserContext, reThrowException: request.ReThrowException, headers: request.Headers)
                    .SelectTopic(request.Input, request.Headers));
        }

        private static ZeroMQTopicInfos GetTopics(ZeroMQESBRequest request) {
            return ZeroMQTopicInfos.New(MessageServiceBase.GetMessageBus(request.UserContext, reThrowException: request.ReThrowException, headers: request.Headers).GetTopics(request.Headers).ToArray());
        }
    }
}
